package com.example.newspublish.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.newspublish.exception.NewsServiceException;
import com.example.newspublish.mapper.CommentMapper;
import com.example.newspublish.pojo.entity.Comment;
import com.example.newspublish.pojo.form.CommentForm;
import com.example.newspublish.pojo.result.ResultCodeEnum;
import com.example.newspublish.service.CommentService;
import com.example.newspublish.util.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
@Slf4j
public class CommentServiceImpl extends ServiceImpl<CommentMapper, Comment> implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public Result addComment(@RequestBody CommentForm commentForm) {
        log.info("新增评论：{}", commentForm);

        Comment comment = new Comment();
        BeanUtils.copyProperties(commentForm, comment);
        if(!StringUtils.isNotEmpty(comment.getCommentContent())) {
            throw new NewsServiceException(ResultCodeEnum.FAIL, "评论内容不能为空");
        }
        int rows = commentMapper.insertComment(comment);
        if(rows != 1) {
            throw new NewsServiceException(ResultCodeEnum.FAIL, "新增评论失败");
        }
        return Result.success("新增评论成功", comment);
    }

    @Override
    public Result getCommentList() {
        List<Comment> commentList = commentMapper.getAllCommentList();
        log.info("评论列表：{}", commentList);
        return Result.success("获取所有评论成功", commentList);
    }////

    @Override
    public void deleteCommentById(Long id) {
        Comment comment = commentMapper.selectById(id);
        if(!ObjectUtils.isNotEmpty(comment)) {
            throw new NewsServiceException(ResultCodeEnum.FAIL, "评论id不存在");
        }
        commentMapper.deleteById(id);
        log.info("删除评论成功");
    }

    public Page<Comment> getCommentsByPage(int pageNum, int pageSize) {
        Page<Comment> commentByPage = new Page<>(pageNum,pageSize);
        return commentMapper.selectPage(commentByPage,null);
    }
}
